﻿using AutoMapper;
using DFGK.IRepository;
using DFGK.IService;
using DFGK_WMS.Model.Dto;
using DFGK_WMS.Model.Dto.YS;
using DFGK_WMS.Model.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace DFGK.Service
{
    public class MaterialPackageReceivingService : BaseService, IMaterialPackageReceivingService
    {
        private readonly IMaterialPackageReceivingRepository _materialPackageReceivingRepository;
        private readonly ISupplierRepository _supplierRepository;
        private readonly IWarehouseRepository _warehouseRepository;
        private readonly IAreaRepository _areaRepository;
        private readonly IReceivingBillRepository receivingBillRepository;
        private readonly IReceivingBillDetailRepository receivingBillDetailRepository;
        private readonly IMaterialRepository materialRepository;
        private readonly IUnitOfWork _unitOfWork;
        public MaterialPackageReceivingService(IMapper mapper, IMaterialPackageReceivingRepository materialPackageReceivingRepository, IUnitOfWork unitOfWork, IMaterialRepository materialRepository, ISupplierRepository supplierRepository, IWarehouseRepository warehouseRepository, IReceivingBillRepository receivingBillRepository, IReceivingBillDetailRepository receivingBillDetailRepository, IAreaRepository areaRepository) : base(mapper)
        {
            _materialPackageReceivingRepository = materialPackageReceivingRepository;
            _unitOfWork = unitOfWork;
            this.materialRepository = materialRepository;
            _supplierRepository = supplierRepository;
            _warehouseRepository = warehouseRepository;
            this.receivingBillRepository = receivingBillRepository;
            this.receivingBillDetailRepository = receivingBillDetailRepository;
            _areaRepository = areaRepository;
        }

        public bool AddOrModefiyMaterialPackageReceiving(ERPReceivingBillDTO model, out string errorMsg)
        {
            var billTypes = 0;
            long waresHouseId = 0;
            int billType = 0;
            errorMsg = string.Empty;
            if (model.BillDetailList == null || !model.BillDetailList.Any())
            {
                errorMsg = "物料列表不能为空！";
                return false;
            }
            // 验证物料项
            foreach (var item in model.BillDetailList)
            {
                var material = materialRepository.QueryEntityWhere(r => r.Code == item.MaterialCode );
                if (material == null)
                {
                    errorMsg = $"物料 {item.MaterialCode} 信息有误！";
                    return false;
                }

                if (item.Qty <= 0)
                {
                    errorMsg = $"物料 {item.MaterialCode} 收货数量不能小于0";
                    return false;
                }

                if (item.Qty % 1 != 0)
                {
                    errorMsg = $"物料 {item.MaterialCode} 收货数量包含小数";
                    return false;
                }
                //根据物料 判断入哪个库
                if (material.TypeName == "Y")
                {
                    waresHouseId = 666038277042181;
                }
                else
                {
                    waresHouseId = 666038409969669;
                }
                    if (!string.IsNullOrEmpty(model.BillType))
                    {
                        if(model.BillType== "收料通知")
                        {
                           billType = 2;
                         }
                        else if(model.BillType == "5")
                    {
                        billType = 5;
                    }
                        else
                        {
                          billType = 1;
                         }
                        
                    }
                   
                

            }

            if (model.OtherTypeCode != null && model.OtherTypeCode != "")
            {
                billType = 5;//为空
            }
            // 获取供应商和库房
            long supplierId = 0;
            var supplierCode = "";
            var supplierName = "";
            var POMode = "";
            if (!string.IsNullOrEmpty(model.SupplierCode))
            {
                var supplier = _supplierRepository.QueryIsEntityWhere(d => d.Code == model.SupplierCode);
                supplierId = supplier.Id;
                supplierCode = supplier.Code;
                supplierName = supplier.Name;
                POMode = supplier.POMode;
            }
            else
            {
                 supplierId = 0;
                 supplierCode = null;
                 supplierName = null;
                 POMode = null;
            }
            var warehouse = _warehouseRepository.QueryEntityById(waresHouseId);

            if (warehouse == null || warehouse.Status != 1)
            {
                errorMsg = "库房不存在或者已被禁用！";
                return false;
            }
            
             
            var are =_areaRepository.QueryEntityWhere(d => d.WhId == waresHouseId);
            // 处理收货单   
            if (waresHouseId == 666038409969669)
            {
                ReceivingBill receivingBill = new()
                {
                    BillNo = model.BillNo,
                    Status = 0,
                    IsDel = false,
                    CreateDate = DateTime.Now,
                    BeginDate = Convert.ToDateTime(model.BillDate),
                    CreateUserId = 0,
                    ModifyUserId = 0,
                    OtherTypeCode = model.OtherTypeCode,
                    BillType = billType,
                    WorkShopCode = model.WorkShopCode,
                    WorkShopName = model.WorkShopName,
                    WarehouseCode = warehouse.Code,
                    WarehouseId = warehouse.Id,
                    WarehouseName = warehouse.Name,
                    SupplierId = supplierId,
                    SupplierName = supplierName,
                    POMode =POMode

                };
                _unitOfWork.BeginTransaction();
                try
                {
                    foreach (var item in model.BillDetailList)
                    {
                        receivingBill.TotalQty = item.Qty;
                        receivingBillRepository.AddEntity(receivingBill);
                        _unitOfWork.SaveChangesEntity();

                        var material = materialRepository.QueryEntityWhere(r => r.Code == item.MaterialCode );
                        var receivingBillDetail = new ReceivingBillDetail
                        {
                            Id = YitIdHelper.NextId(),
                            MaterialName = material.Name,
                            MaterialCode = material.Code,
                            Qty = item.Qty,
                            MaterialId = material.Id,
                            MaterialTypeName = material.MaterialCategoryName,
                            SupplierId = receivingBill.SupplierId,  
                            SupplierName = receivingBill.SupplierName,
                            ReceivedQty = 0,
                            BatchNo = item.BatchNo ?? "CG" + DateTime.Now.ToString("yyyyMMddHHmmss"),
                            CreateDate = DateTime.Now,
                            BillNo = receivingBill.BillNo,
                            BillId = receivingBill.Id,
                            ModelSpec= material.ModelSpec,
                            //质量状态（Y：合格/N：不合格，不合格只能入不良品仓库）
                            IsNeedQc = item.ISPass == null ? (bool?)null : (item.ISPass == "Y"),
                            ISPass =item.ISPass,
                            Status = 0
                        };
                        receivingBillDetailRepository.AddEntity(receivingBillDetail);
                       
                    }
                    _unitOfWork.SaveChangesEntity();
                    _unitOfWork.CommitChanges();
                    return true;
                }
                catch (Exception)
                {
                    _unitOfWork.RollbackChanges();
                    throw;
                }
            }
            else
            {
                List<MaterialPackageReceiving> materialPackages = model.BillDetailList.Select(item =>
                {
                    var material = materialRepository.QueryEntityWhere(r => r.Code == item.MaterialCode );
                    return new MaterialPackageReceiving
                    {
                        Id = YitIdHelper.NextId(),
                        BillNo = model.BillNo,
                        //StoLocation = model.StoLocation,
                        SupplierId = supplierId,
                        SupplierName = supplierName,
                        
                        //BillType = item.BatchNo == null ? 1 : 2, // 采购 or 收料
                        BillType = billType,
                        BatchNo = item.BatchNo ?? "CG" + DateTime.Now.ToString("yyyyMMddHHmmss"),
                        OtherTypeCode = model.OtherTypeCode,
                        //Receiver = model.Receiver,
                        WarehouseId = warehouse.Id,
                        WarehouseCode = warehouse.Code,
                        BeginDate = Convert.ToDateTime(model.BillDate),
                        MaterialId = material.Id,
                        MaterialName = material.Name,
                        MaterialCode = material.Code,
                        POMode = POMode,
                        AllQty = item.Qty,
                        WorkShopCode = model.WorkShopCode,
                        WorkShopName=model.WorkShopName,
                        IsNeedQc = item.ISPass == null ? (bool?)null : (item.ISPass == "Y"),
                        CreateDate = DateTime.Now,
                        PakcRevevingStatus = 0
                    };

                }).ToList();

                _materialPackageReceivingRepository.AddEntityList(materialPackages);
                return _unitOfWork.SaveChangesEntity();
            }
        }
        //生产任务单
        public bool AddProductionOrder(ERPProductionOrderDto model, out string errorMsg)
        {
            long waresHouseId = 0;
            errorMsg = string.Empty;
           
            // 验证物料项
            
                var material = materialRepository.QueryEntityWhere(r => r.Code == model.MaterialCode );
                if (material == null)
                {
                    errorMsg = $"物料 {model.MaterialCode} 信息有误！";
                    return false;
                }
                if (model.Qty <= 0)
                {
                    errorMsg = $"物料 {model.MaterialCode} 收货数量不能小于0";
                    return false;
                }

                if (model.Qty % 1 != 0)
                {
                    errorMsg = $"物料 {model.MaterialCode} 收货数量包含小数";
                    return false;
            }
            //根据物料 判断入哪个库
            if (material.TypeName == "Y")
            {
                waresHouseId = 666038277042181;//立库
            }
            else
            {
                waresHouseId = 666038409969669;//平库
            }
            var billTypes = 0;
            if (model.OtherTypeCode != null && model.OtherTypeCode != "")
            {
                billTypes = 5;//为空
            }
            else
            {
                billTypes = 3;//生产任务单
             }
            var warehouse = _warehouseRepository.QueryEntityById(waresHouseId);

            if (warehouse == null || warehouse.Status != 1)
            {
                errorMsg = "库房不存在或者已被禁用！";
                return false;
            }
            var are = _areaRepository.QueryEntityWhere(d => d.WhId == waresHouseId);
            // 处理收货单   
            if (waresHouseId == 666038409969669)
            {
                _unitOfWork.BeginTransaction();
                try
                {
                    ReceivingBill receivingBill = new()
                {
                    BillNo = model.BillNo,
                    WorkShopCode = model.WorkShopCode,
                    WorkShopName = model.WorkShopName,
                    BeginDate= model.BeginDate,
                    EndDate= model.EndDate,
                    OtherTypeCode=model.OtherTypeCode,
                    Status = 0,
                    IsDel = false,
                    CreateDate = DateTime.Now,
                    CreateUserId = 0,
                    ModifyUserId = 0,
                    BillType = billTypes,//生产任务单
                    WarehouseCode = warehouse.Code,
                    WarehouseId = warehouse.Id,
                    WarehouseName = warehouse.Name,
                    BatchManager=model.BatchManager,
                     TotalQty=model.Qty

                };
                     
                        receivingBillRepository.AddEntity(receivingBill);
                        _unitOfWork.SaveChangesEntity();

                        
                        var receivingBillDetail = new ReceivingBillDetail
                        {
                            Id = YitIdHelper.NextId(),
                            MaterialName = material.Name,
                            MaterialCode = material.Code,
                            Qty = model.Qty,
                            MaterialId = material.Id,
                            MaterialTypeName = material.MaterialCategoryName,
                            SupplierId = receivingBill.SupplierId,
                            SupplierName = receivingBill.SupplierName,
                            ReceivedQty = 0,
                            //BatchNo = string.IsNullOrEmpty(model.BatchNo) ? "" : model.BatchNo ?? "CG" + DateTime.Now.ToString("yyyyMMddHHmmss"),
                            BatchNo = string.IsNullOrEmpty(model.BatchNo) ? "" : model.BatchNo,
                            CreateDate = DateTime.Now,
                            ModelSpec = material.ModelSpec,
                            BillNo = receivingBill.BillNo,
                            BillId = receivingBill.Id,
                            Status = 0
                        };
                        receivingBillDetailRepository.AddEntity(receivingBillDetail);
                    _unitOfWork.SaveChangesEntity();
                    _unitOfWork.CommitChanges();
                    return true;
                }
                catch (Exception)
                {
                    _unitOfWork.RollbackChanges();
                    throw;
                }
            }
            else
            {
               

                var materialPackage = new MaterialPackageReceiving
                {
                    Id = YitIdHelper.NextId(),  // 生成唯一ID
                    BillNo = model.BillNo,  // 生产任务单编号
                   
                    BatchNo = string.IsNullOrEmpty(model.BatchNo) ? "" : model.BatchNo,
                    WarehouseId = warehouse.Id,  // 仓库ID
                    WarehouseCode = warehouse.Code,  // 仓库代码
                    BeginDate = model.BeginDate,
                    EndDate= model.EndDate,
                    OtherTypeCode=model.OtherTypeCode,
                    MaterialId = material.Id,  // 物料ID
                    MaterialName = material.Name,  // 物料名称
                    MaterialCode = material.Code,  // 物料编码
                    BatchManager=model.BatchManager,
                    WorkShopCode=model.WorkShopCode,
                    Receiver=material.ModelSpec,
                    WorkShopName=model.WorkShopName,
                    BillType=3,
                    AllQty = model.Qty,  // 物料收货数量
                    CreateDate = DateTime.Now,  // 创建日期
                    PakcRevevingStatus = 0  // 包装接收状态
                };

                _materialPackageReceivingRepository.AddEntity(materialPackage);
                return _unitOfWork.SaveChangesEntity();
            }

        }
        public bool DelMaterialPackageReceiving(long Id)
        {
            var Quote = _materialPackageReceivingRepository.QueryEntityById(Id);
            if (Quote == null)
            {
                return false;
            }
            _materialPackageReceivingRepository.DelEntity(Quote);
            return _unitOfWork.SaveChangesEntity();
        }
        public MaterialPackageReceiving? MaterialPackageReceivingById(long Id)
        {
            return _materialPackageReceivingRepository.QueryEntityById(Id);
        }

        public MaterialPackageReceiving? GetMaterialPackageReceiving(long Id)
        {
            return _materialPackageReceivingRepository.QueryEntityById(Id);
        }

        public List<MaterialPackageReceiving> GetMaterialPackageReceivingData(string? ordersn, string? materialkey, string? WorkShopName, out int totalCount, int? status = 0, int pageIndex = 1, int pageSize = 15)
        {
            var list = _materialPackageReceivingRepository.GetEntityAlls();
            if (!string.IsNullOrEmpty(ordersn))
            {
                list = list.Where(d => d.BillNo.Contains(ordersn));
            }
            if (!string.IsNullOrEmpty(materialkey))
            {
                list = list.Where(d => d.MaterialCode.Contains(materialkey) || d.MaterialName.Contains(materialkey) || d.Receiver.Contains(materialkey));
            }
            if (!string.IsNullOrEmpty(WorkShopName))
            {
                list = list.Where(d => d.WorkShopName.Contains(WorkShopName));
            }
            if (status != null)
            {
                list = list.Where(d => d.PakcRevevingStatus == status);
            }
            totalCount = list.Count();
           list = list.OrderByDescending(d => d.CreateDate).Skip((pageIndex - 1) * pageSize).Take(pageSize) ;
            return list.ToList();
        }

        public bool UpdateMaterialPackageReceiving(MaterialPackageReceiving u)
        {
            // 查询当前实体是否存在
            var existingEntity = _materialPackageReceivingRepository.QueryIsEntityWhere(x => x.Id == u.Id);

            if (existingEntity != null)
            {
                // 如果实体存在，则进行更新
                _materialPackageReceivingRepository.UpdEntity(u);
                return _unitOfWork.SaveChangesEntity();
            }
            else
            {
                // 如果实体不存在，返回 false，表示更新失败
                return false;
            }
        }
    }
}
